package com.suliu.practice.thread;

/**
 * 好像有点问题
 * @author Administrator
 *
 */
public class WaitNotifySample {
	public static void main(String[] args) {
		Sample sample=new Sample();
		Thread t1=new IncreaThread(sample);
		Thread t2=new DecreaThread(sample);
		Thread t3=new IncreaThread(sample);
		Thread t4=new DecreaThread(sample);
		
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
}
class Sample{
	private int number=0;
	public synchronized void increase(){
		while(0!=number){//用while不用if。如果用if，不是2个线程而是4个线程，就乱了，不是10101010了。
			try {
				wait();//wait(会释放锁)，调用的时候必须已经获得对象的锁，所以必须放在synchronized代码块中。final的，不可重写。
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		number++;//sleep不会释放锁
		System.out.println(number);
		notify();//随机唤醒一个等待的线程。调用的时候必须已经获得对象的锁，所以必须放在synchronized代码块中。final的，不可重写。
	}
	public synchronized void decrease(){
		while(0==number){
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		number--;
		System.out.println(number);
		notify();
	}
}
class IncreaThread extends Thread{
	Sample sample;
	public IncreaThread(Sample sample){
		this.sample=sample;
	}
	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			sample.increase();
		}
	}
}
class DecreaThread extends Thread{
	Sample sample;
	public DecreaThread(Sample sample){
		this.sample=sample;
	}
	@Override
	public void run() {
		for (int i = 0; i < 20; i++) {
			sample.decrease();
		}
	}
}
